<?php
$request_url = "https://api.eveonline.com/char/WalletJournal.xml.aspx?keyID=14566&vCode=CrQRyEPLTld8ep3Z2tiklfKnMU1yMh08xLFKp8rnF0IkvZ6DeNSJVAVqSwpz4ALU&characterID=90440624&rowCount=2560";
$payment_code_regex = "/==![0-9A-Fa-f]{128}/";
$corp_name="Cross Barret";


//connect to DB
if (!($class_manager_db = mysql_connect("localhost", "class_manager", "allun33d!"))) {
	echo "Unable to connect to database. ".mysql_error($class_manager_db);
}
if (!mysql_select_db("class_manager", $class_manager_db)) {
	echo "Database is not available.";
}
if (!mysql_query("SET NAMES 'utf8' COLLATE 'utf8_roman_ci'", $class_manager_db)) {
	echo "Setting charset failed.";
}

//find last refID from DB, not sure if refIDs will ever loop around in 3021 so taking timestamp into account as well
$last_refID=0;
$result = mysql_query("select api_refID, timestamp from transactions order by api_refID desc, timestamp desc limit 1", $class_manager_db) or die(mysql_error($class_manager_db));
if(mysql_num_rows($result)>0){
	$line=mysql_fetch_array($result, MYSQL_ASSOC);
	if($line["api_refID"]!==NULL)
		$last_refID=(int)$line["api_refID"];
}



$api_reply = simplexml_load_file($request_url) or die("Feed not loading.");
$done=false;
while(sizeof($api_reply->result->rowset->row)>0){

	foreach ($api_reply->result->rowset->row as $row){
		if(((int)$row["refID"])==$last_refID){
			echo "found last refID: ".$row["refID"]."<br>";
			$done=true;//cant break yet, the api doesnt guarentee that refIDs are sorted...fucking CCP
		}
		
		if(preg_match($payment_code_regex,$row["reason"],$matches)){
			echo "found key<br>";
			mysql_query("LOCK TABLE transactions WRITE", $class_manager_db) or die(mysql_error($class_manager_db));
			//check if it already exists
			$result = mysql_query("select api_refID from transactions where api_refID='".$row["refID"]."' and timestamp='".$row["date"]."'", $class_manager_db) or die(mysql_error($class_manager_db));
			if(mysql_num_rows($result)==0){
				if($row["ownerName1"]==$corp_name){
					$character_name=$row["ownerName2"];
				}
				else {
					$character_name=$row["ownerName1"];
				}
				
				//add to DB
				mysql_query("INSERT INTO transactions (payment_code, api_refID, character_name, amount, timestamp)
				VALUES ('".$matches[0]."', '".$row["refID"]."', '$character_name', '".$row["amount"]."', '".$row["date"]."')", $class_manager_db) or die(mysql_error($class_manager_db));
			}
			mysql_query("UNLOCK TABLES", $class_manager_db) or die(mysql_error($class_manager_db));
		}
		
		
		//echo $row["refID"]."<br>";
		if(!isset($fromID) || ((int)$row["refID"])<$fromID)
			$fromID=((int)$row["refID"]);
	}
	if($done){
		echo "broke<br>";
		break;
	}
	
	$repeat_request_url=$request_url."&fromID=".$fromID;
	$api_reply = simplexml_load_file($repeat_request_url) or die("Feed not loading.");
}



//echo "<pre>"; var_dump($api_reply); echo "</pre>";

?>